package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.domain.QuestionAnswerTemplate;
import cn.wolfcode.luowowo.search.repository.QuestionAnswerTemplateRepository;
import cn.wolfcode.luowowo.search.service.IQuestionAnswerTemplateService;
import cn.wolfcode.luowowo.search.vo.QAStatisVO;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.search.aggregations.bucket.composite.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.*;

@Service
public class QuestionAnswerTemplateServiceImpl implements IQuestionAnswerTemplateService{

    @Autowired
    private QuestionAnswerTemplateRepository repository;

    @Override
    public void save(QuestionAnswerTemplate template) {
        repository.save(template);
    }

    @Override
    public List<QAStatisVO> queryQARank() {
//        List<QAStatisVO> data = new ArrayList<>();
        //先查询出主题ID，主题名字，目的地数量存放在theme中
        List<QAStatisVO> data = this.queryQAStatisVOList("userId", "questionId","username","headUrl","level", "answerRank");
        //通过themeId查询出目的地ID和name
//        Map<String,Object> map = null;
//        for (QAStatisVO vo : list) {
//            map = new HashMap<>();
//            List<QAStatisVO> vos = this.getUserByUserId(vo.getId());
//            map.put("user",vo);
//            map.put("dests",vos);
//            data.add(map);
//        }
        return data;

    }
    private List<QAStatisVO> queryQAStatisVOList(String userIdField,String questionIdField,String usernameField,String headUrlField,String levelField,String answerRankField){
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();

        TermsValuesSourceBuilder userIdSource = new TermsValuesSourceBuilder("userId");
        userIdSource.field(userIdField);
        sources.add(userIdSource);


        TermsValuesSourceBuilder usernameSource = new TermsValuesSourceBuilder("username");
        usernameSource.field(usernameField);
        sources.add(usernameSource);

//        TermsValuesSourceBuilder questionIdSource = new TermsValuesSourceBuilder("questionId");
//        questionIdSource.field(questionIdField);
//        sources.add(questionIdSource);

        TermsValuesSourceBuilder headUrlSource = new TermsValuesSourceBuilder("headUrl");
        headUrlSource.field(headUrlField);
        sources.add(headUrlSource);

        TermsValuesSourceBuilder levelSource = new TermsValuesSourceBuilder("level");
        levelSource.field(levelField);
        sources.add(levelSource);

        CompositeAggregationBuilder aggregationBuilder = new CompositeAggregationBuilder(answerRankField,sources);
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.addAggregation(aggregationBuilder);

        //设置size为0，但spring-data限制了size必须大于等于1
        builder.withPageable(PageRequest.of(0,1));
        builder.withIndices(QuestionAnswerTemplate.INDEX_NAME);
        builder.withTypes(QuestionAnswerTemplate.TYPE_NAME);


        AggregatedPage<QuestionAnswerTemplate> search = (AggregatedPage<QuestionAnswerTemplate>) repository.search(builder.build());
        InternalComposite themeGroup = search.getAggregations().get(answerRankField);
        List<QAStatisVO> list = new ArrayList<>();
        for (CompositeAggregation.Bucket bucket : themeGroup.getBuckets()) {
            Long userId = Long.parseLong(bucket.getKey().get("userId").toString());
            String username = bucket.getKey().get("username").toString();
            String headUrl = bucket.getKey().get("headUrl").toString();
            Integer level = Integer.parseInt(bucket.getKey().get("level").toString());
            Long count = bucket.getDocCount();

            QAStatisVO qAStatisVO = new QAStatisVO();
            qAStatisVO.setCount(count);
            qAStatisVO.setId(userId);
            qAStatisVO.setName(username);
            qAStatisVO.setHeadUrl(headUrl);
            qAStatisVO.setLevel(level);
            list.add(qAStatisVO);
        }
        //排序
        Collections.sort(list, new Comparator<QAStatisVO>() {
            @Override
            public int compare(QAStatisVO o1, QAStatisVO o2) {
                Long ret = o2.getCount() - o1.getCount();
                return ret.intValue();
            }
        });
        //取前十个
        if(list.size() > 10){
            list = list.subList(0,10);
        }
        return list;
    }

    private List<QAStatisVO> getUserByUserId(Long userId){
        List<QAStatisVO> vos = new ArrayList<>();
        List<QuestionAnswerTemplate> templates = repository.findByUserId(userId);
        List<String> list = new ArrayList<>();
        //去除重复
        for (QuestionAnswerTemplate template : templates) {
            if(!list.contains(template.getUsername())){
                QAStatisVO qaStatisVO = new QAStatisVO();
                qaStatisVO.setId(template.getUserId());
                qaStatisVO.setName(template.getUsername());
                vos.add(qaStatisVO);
                list.add(template.getUsername());
            }
        }
        return vos;
    }
}
